package com.example.utils;

import com.example.monitor.ConnMonitorThread;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class HiveUtils {

    private static String driverName = "org.apache.hive.jdbc.HiveDriver";
    // 使用高可用方式连接hive
    public static String url = String.format("jdbc:hive2://%s/ods;" +
            "serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2",
            "172.19.6.12:2181,172.19.6.13:2181,172.19.6.14:2181");
    public static String user = "customer_pro";
    public static String password = "customer_pro@22";

    public static volatile Connection conn = null;

    static {
        try {
            Class.forName(driverName);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();
        }
    }

    /**
     * 获取hive数据库连接
     * @return
     * @throws SQLException
     */
    public static Connection getConn() throws SQLException {
        if(conn == null || conn.isClosed()){
            conn = DriverManager.getConnection(url, user, password);
            conn.setAutoCommit(true);
        }
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    public HiveUtils() {
        try {
            conn = DriverManager.getConnection(url, user, password);
            conn.setAutoCommit(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();
        }
    }
}
